package com.lagou.edu.controller;

import com.lagou.edu.service.AuthCodeService;
import com.lagou.edu.service.EmailServiceFeignClient;
import com.lagou.edu.service.UserServiceFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("api/code")
public class AuthCodeController {


    @Autowired
    AuthCodeService authCodeService;
    @Autowired
    UserServiceFeignClient userServiceFeignClient;

    @Autowired
    EmailServiceFeignClient emailServiceFeignClient;



    @RequestMapping("/create/{email}")
    public boolean createCode(@PathVariable String email){
        //查询邮箱是否注册过
        boolean registered = userServiceFeignClient.isRegistered(email);
        if (registered) {
            System.out.println("邮箱已经注册过，email：" + email);
            //已经注册过
            return false;
        }
        System.out.println("邮箱未注册过，email：" + email);
        //生成验证码
        String code = authCodeService.createCode(email);
        if (null == code || code.length() != 6) {
            //验证码生成失败
            return false;
        }
        System.out.println("生成验证码，email：" + email + "；code：" + code);

        //发送验证码邮件
        return emailServiceFeignClient.sendEmail(email, code);
    }


    @RequestMapping("/validate/{email}/{code}")
    public int validate(@PathVariable String email, @PathVariable String code){
        return authCodeService.validate(email, code);
    }
}
